<template>
  <div class="app-container">
    <!-- 桌面端布局 -->
    <el-row :gutter="10" v-if="!isMobile">
      <el-col :span="24">
        <div class="course_content">
          <el-row type="flex" justify="around" style="width: 100%">
            <el-col :span="20">
              <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
                <el-form-item label="关联培训" prop="exam">
                  <el-select v-model="queryParams.train_task" placeholder="请选择.." clearable filterable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in trainOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <el-form-item label="培训人员" prop="user">
                  <el-select v-model="queryParams.user" placeholder="请选择.." filterable clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                  </el-select>
                </el-form-item>
                <!-- <el-form-item label="培训状态" prop="state">
                  <el-select v-model="queryParams.state" placeholder="请选择.." clearable size="small" @change="handleQuery">
                    <el-option v-for="dict in stateOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item> -->
                <el-form-item label="培训结果" prop="is_passed">
                  <el-select v-model="queryParams.is_passed" placeholder="请选择.." clearable size="small"
                    @change="handleQuery">
                    <el-option v-for="dict in passedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                      :value="dict.dictValue" />
                  </el-select>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" size="mini" @click="handleQuery" :style="{
                    backgroundColor: theme,
                    borderColor: theme
                  }">搜索</el-button>
                  <el-button size="mini" @click="resetQuery">清空</el-button>
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mb8">
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
          <el-table :data="List" style="width: 100%" v-loading="loading" :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }">
            <el-table-column label="培训名称" prop="name"></el-table-column>
            <el-table-column label="关联课程">
              <template slot-scope="scope">
                {{ scope.row.course.name }}
              </template>
            </el-table-column>
            <el-table-column label="培训人员">
              <template slot-scope="scope">
                {{ scope.row.user.name }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="培训次数" prop="user"></el-table-column> -->


            <el-table-column label="培训结果" prop="is_passed" :formatter="resultFormatter"></el-table-column>
            <el-table-column label="创建时间">
              <template slot-scope="scope">
                <span>{{ scope.row.create_time }}</span>

              </template>
            </el-table-column>
            <!-- <el-table-column label="培训状态">
              <template slot-scope="scope">
                <span v-if="scope.row.state == 2 && scope.row.is_submited == false">缺考</span>
                <span v-else>{{ scope.row.state_name }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="培训详情" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  fontWeight: 'bold'
                }" v-hasPermi="['train:results:query']" @click="handleResult(scope.row)">
                  查阅</el-button>


              </template>
            </el-table-column> -->
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size"
            @pagination="getList" />
          <!-- 添加或修改菜单对话框 -->
          <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :style="{ color: theme }">

            <el-card>
              <el-descriptions class="margin-top" :column="3" border>
                <el-descriptions-item v-if="formData.name && formData.name !== undefined">
                  <template slot="label"> 培训名称 </template>
                  {{ formData.name }}
                </el-descriptions-item>
                <el-descriptions-item
                  v-if="formData && formData.course !== undefined && formData.course.name !== undefined">
                  <template slot="label"> 关联课程 </template>
                  {{ formData.course.name }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.user !== undefined">
                  <template slot="label"> 培训人员 </template>
                  {{ formData.user.name }}
                </el-descriptions-item>
                <el-descriptions-item v-if="formData.user !== undefined">
                  <template slot="label"> 培训情况 </template>

                  <el-row v-if="formData.Chapter" v-for="item in formData.Chapter" :key="item.id">
                    <el-col :span="12">{{ item.name }}</el-col>
                    <el-col :span="12" :style="item.is_passed ? { color: theme } : { color: 'red' }">{{
                      item.is_passed |
                      passedFilter }}</el-col>
                  </el-row>
                </el-descriptions-item>


              </el-descriptions>
            </el-card>


            <div slot="footer" class="dialog-footer">
              <el-button type="primary" size="small" @click="cancel">确 定</el-button>

            </div>
          </el-dialog>
        </div>
      </el-col>
    </el-row>
    
    <!-- 移动端布局 -->
    <template v-if="isMobile">
      <!-- 显示骨架屏 -->
      <mobile-skeleton 
        v-if="loading" 
        :showSearch="true" 
        :searchFields="3"
        :cardsCount="3"
        :showPagination="total > 0"
      />
      
      <div v-else class="course_content">
        <!-- 移动端搜索表单 -->
        <el-row type="flex" justify="around" style="width: 100%" class="mobile-search">
          <el-col :span="24">
            <el-form :model="queryParams" ref="queryForm" v-show="showSearch" class="mobile-form">
              <el-form-item label="关联培训" prop="exam">
                <el-select 
                  v-model="queryParams.train_task" 
                  placeholder="请选择.." 
                  clearable 
                  filterable 
                  size="small"
                  @change="handleQuery" 
                  style="width: 100%">
                  <el-option v-for="dict in trainOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="培训人员" prop="user">
                <el-select 
                  v-model="queryParams.user" 
                  placeholder="请选择.." 
                  filterable 
                  clearable 
                  size="small"
                  @change="handleQuery" 
                  style="width: 100%">
                  <el-option v-for="dict in userOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="培训结果" prop="is_passed">
                <el-select 
                  v-model="queryParams.is_passed" 
                  placeholder="请选择.." 
                  clearable 
                  size="small"
                  @change="handleQuery" 
                  style="width: 100%">
                  <el-option v-for="dict in passedOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue" />
                </el-select>
              </el-form-item>
              
              <el-form-item class="mobile-form-buttons">
                <el-row :gutter="10" style="width: 100%">
                  <el-col :span="12">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="handleQuery" 
                      :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                        width: '100%'
                }">搜索</el-button>
                  </el-col>
                  <el-col :span="12">
                    <el-button 
                      size="small" 
                      @click="resetQuery" 
                      style="width: 100%;">清空</el-button>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        
        <!-- 移动端工具栏 - 修改为水平布局，适合手机端用户操作的图标按钮 -->
        <div class="mobile-toolbar-wrapper">
          <div class="mobile-toolbar">
            <div class="mobile-toolbar-buttons">
              <el-button 
                type="text"
                class="mobile-tool-btn"
                @click="toggleSearch">
                <i class="el-icon-search" :style="{ color: showSearch ? theme : '' }"></i>
                <span>搜索</span>
              </el-button>
              <el-button 
                type="text" 
                class="mobile-tool-btn"
                @click="getList">
                <i class="el-icon-refresh" :style="{ color: theme }"></i>
                <span>刷新</span>
              </el-button>
              <el-button 
                type="text" 
                class="mobile-tool-btn"
                @click="resetQuery">
                <i class="el-icon-delete" :style="{ color: theme }"></i>
                <span>清空</span>
              </el-button>
            </div>
          </div>
        </div>
        
        <!-- 移动端卡片视图 -->
        <div class="mobile-card-view">
          <!-- 暂无数据提示卡片 -->
          <el-card v-if="List.length === 0" class="empty-data-card" shadow="hover">
            <div class="empty-data-content">
              <i class="el-icon-document" :style="{ color: theme }"></i>
              <p>暂无培训结果数据</p>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleQuery" 
                :style="{
                  backgroundColor: theme,
                  borderColor: theme,
                  marginTop: '10px'
                }">
                刷新数据
              </el-button>
          </div>
          </el-card>
          
          <el-card v-else v-for="(item, index) in List" :key="index" class="mobile-card" shadow="hover">
            <div slot="header" class="card-header">
              <div class="card-title" :style="{ color: theme }">{{ item.name }}</div>
            </div>
            <div class="card-content">
              <div class="info-list">
                <div class="info-item">
                  <span class="label">关联课程：</span>
                  <span class="value">{{ item.course.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">培训人员：</span>
                  <span class="value">{{ item.user.name }}</span>
                </div>
                <div class="info-item">
                  <span class="label">培训结果：</span>
                  <span class="value">
                    <el-tag size="mini" :type="item.is_passed ? 'success' : 'danger'">
                      {{ item.is_passed ? '通过' : '未通过' }}
                    </el-tag>
                  </span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ item.create_time }}</span>
                </div>
              </div>
              
              <div class="exam-details" v-if="expandedCards[index]">
                <div class="details-section" v-if="item.Chapter && item.Chapter.length > 0">
                  <div class="details-title">培训章节完成情况</div>
                  <div class="chapter-list">
                    <div v-for="(chapter, chapIdx) in item.Chapter" :key="chapIdx" class="chapter-item">
                      <span class="chapter-name">{{ chapter.name }}</span>
                      <span class="chapter-status" :class="{ 'passed': chapter.is_passed }">
                        {{ chapter.is_passed | passedFilter }}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="mobile-card-actions">
                <el-button type="text" size="small" @click.stop="expandCard(index)">
                  {{ expandedCards[index] ? '收起' : '查看详情' }}
                  <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
                </el-button>
              </div>
            </div>
          </el-card>
          
          <!-- 移动端分页 -->
          <div class="mobile-pagination" v-if="total > 0">
            <div class="mobile-pagination-wrapper">
              <!-- 第一行：总数和每页条数 -->
              <div class="pagination-row top-row">
                <span class="el-pagination__total">共 {{ total }} 条</span>
                <el-select 
                  v-model="queryParams.page_size" 
                  size="mini" 
                  class="el-pagination__sizes"
                  @change="handleSizeChange">
                  <el-option
                    v-for="item in [10, 20, 30, 50]"
                    :key="item"
                    :label="`${item}条/页`"
                    :value="item">
                  </el-option>
                </el-select>
              </div>
              
              <!-- 第二行：页码导航 -->
              <div class="pagination-row bottom-row">
                <el-pagination
                  background
                  @current-change="handleCurrentChange"
                  :current-page="queryParams.page"
                  :page-size="queryParams.page_size"
                  layout="prev, pager, next, jumper"
                  :total="total">
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
import { markingExam } from "@/api/vadmin/exam/making";
import { getTrain, getTrainList } from "@/api/vadmin/train/train";
import { listUser } from "@/api/vadmin/permission/user";
import CourseTree from "@/components/CourseTree";
import MobileSkeleton from "@/components/MobileSkeleton";
import "@/assets/styles/mobile/exam.scss"; // 引入移动端公共样式

export default {
  name: "results",
  components: { CourseTree, MobileSkeleton },
  data() {
    return {
      title: "培训详情",
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 是否显示弹出层
      open: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      courseList: null,
      form: {},
      queryParams: {
        // courseId: "",
        page: 1,
        page_size: 10,
      },
      formData: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      stateOptions: [
        {
          dictValue: 0,
          dictLabel: "未开始",
        },
        {
          dictValue: 1,
          dictLabel: "进行中",
        },
        {
          dictValue: 2,
          dictLabel: "已结束",
        },
      ],
      submitedOptions: [
        {
          dictValue: true,
          dictLabel: "是",
        },
        {
          dictValue: false,
          dictLabel: "否",
        },
      ],
      markedOptions: [
        {
          dictValue: true,
          dictLabel: "是",
        },
        {
          dictValue: false,
          dictLabel: "否",
        },
      ],
      passedOptions: [
        {
          dictValue: true,
          dictLabel: "通过",
        },
        {
          dictValue: false,
          dictLabel: "未通过",
        },
      ],
      userOptions: [],
      trainOptions: [],
      List: [],
      courseOptions: [],
      courseName: undefined,
      intervalId: null,
      expandedCards: {},
      isMobile: false,
      mediaQueryList: null
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  filters: {
    subFilter(value) {
      if (value) {
        return "已交卷";
      } else {
        return "未交卷";
      }
    },
    passedFilter(val) {
      var state = {
        'null': '未通过',
        'true': '已通过',
        'false': '未通过'
      }
      return state[val]
    }
  },

  created() {
    this.getBasicData();
    if (this.$route.query.exam) {
      this.queryParams.exam = Number(this.$route.query.exam);
      this.getList();
    } else {
      this.getList();
    }
  },
  
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },

  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      getTrainList(this.queryParams).then((response) => {
        this.List = response.results;
        this.total = response.count;
        this.loading = false;
      }).catch(err=>{
        this.loading = false;
        this.$message.error('请求超时，请稍后再试');
      })
    },
    getBasicData() {
      getTrain({ page_size: 10000, page: 1 }).then((response) => {
        this.trainOptions = response.results;
      });

      listUser({ page_size: 10000, page: 1 }).then((response) => {
        this.userOptions = response.results;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.name_wd = "";
      this.queryParams.content_wd = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /*去考试 */
    handlePaperDetail(row) {
      // console.log(2222, row)
      this.$router.push({
        name: "paperDetail",
        params: { id: row.id },
      });
    },
    /*新增考试 */
    handleAdd() {
      this.$router.push({ name: "Newexam" });
    },
    /*修改试卷 */
    handleUpdate(row) {
      this.$router.push({ name: "Newexam", params: { id: row.id } });
    },
    resultFormatter(value) {
      if (value.is_passed == true) {
        return "通过";
      } else if (value.is_passed == false) {
        return "未通过";
      }
    },
    /*学习详情 */
    handleResult(row) {
      this.open = true;
      this.formData = row
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    // 切换卡片展开状态
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    handleSizeChange(size) {
      this.queryParams.page_size = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    // 添加切换搜索显示状态的方法
    toggleSearch() {
      this.showSearch = !this.showSearch;
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
  padding: 0;
}

.form-buttons {
  display: flex;
  justify-content: space-between;
  
  .el-button + .el-button {
    margin-left: 0;
  }
}

.mobile-card-view {
  margin-top: 15px;
  
  .card-content {
    .chapter-list {
      margin-top: 10px;
      
      .chapter-item {
        display: flex;
        justify-content: space-between;
        margin-bottom: 8px;
        padding-bottom: 8px;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          margin-bottom: 0;
          padding-bottom: 0;
          border-bottom: none;
        }
        
        .chapter-name {
          flex: 1;
        }
        
        .chapter-status {
          color: #f56c6c;
          
          &.passed {
            color: #67c23a;
          }
        }
      }
    }
    
    .details-title {
      font-weight: bold;
      margin-bottom: 10px;
      padding-bottom: 8px;
      border-bottom: 1px solid #ebeef5;
    }
    
    .mobile-card-actions {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 15px;
      padding-top: 10px;
      border-top: 1px solid #ebeef5;
      
      .el-button {
        width: 100%;
        padding: 8px 0;
        margin: 0;
        font-size: 13px;
        
        i {
          margin-left: 5px;
          font-weight: bold;
        }
      }
    }
  }
}

/* 暂无数据卡片样式 */
.empty-data-card {
  margin-bottom: 15px;
  text-align: center;
  
  .empty-data-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30px 0;
    
    i {
      font-size: 48px;
      margin-bottom: 15px;
      opacity: 0.5;
    }
    
    p {
      font-size: 16px;
      color: #909399;
      margin-bottom: 15px;
    }
    
    .el-button {
      width: 120px;
    }
  }
}

.mobile-form-buttons {
  margin-bottom: 0;
  width: 100%;
  
  .el-row {
    margin-left: 0 !important;
    margin-right: 0 !important;
  }
  
  .el-button {
    margin-left: 0;
    height: 36px;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .mobile-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 15px;
      
      label {
        display: block;
        margin-bottom: 5px;
      }
      
      .el-select {
        width: 100%;
      }
    }
  }
  
  .mobile-search {
    margin-bottom: 15px;
  }
  
  /* 移动端工具栏样式 */
  .mobile-toolbar-wrapper {
    margin: 10px 0 15px;
  }

  .mobile-toolbar {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.12);
    
    .mobile-toolbar-buttons {
      display: flex;
      justify-content: space-between;
      width: 100%;
      
      .mobile-tool-btn {
        flex: 1;
        text-align: center;
        margin: 0;
        padding: 10px 0;
        font-size: 12px;
        border-right: 1px solid #f0f0f0;
        height: auto;
        color: #606266;
        
        &:last-child {
          border-right: none;
        }
        
        i {
          display: block;
          margin: 0 auto 5px;
          font-size: 18px;
        }
        
        span {
          display: block;
          font-size: 12px;
        }
      }
    }
  }
}
</style>